
var fm = Ext.form;
var base_url = '<?php echo base64_decode($_GET['baseUrl']);?>';
var total_row = 20;
var order_status = '<?php echo $_GET['status'];?>';
var proxy = new Ext.data.ScriptTagProxy({
    api: {
        read : base_url+'admin/contact/grid.html?status='+order_status,
        create : base_url+'admin/contact/add.html',
        update: base_url+'admin/contact/add.html',
        destroy: base_url+'admin/contact/delete.html'
    },
    listeners:{
        'write': function(){
            //window.location.href = '/admin/contact/index/'+order_status;
            store.reload({
                params: {
                    start: 0,
                    limit: total_row
                }
            });
        }
     }
});

var writer = new Ext.data.JsonWriter({
    encode: true
});

var store = new Ext.data.JsonStore({
    start : 'start',
    remoteSort: true,
    totalProperty: 'total',
    proxy: proxy,
    root: 'data',
    fields : [
                {name: 'id'},
                {name: 'name'},
                {name: 'email'},
                {name: 'company'},
                {name: 'message_subject'},
                {name: 'contact_day', type: 'date'},
                {name: 'status'},
                {name: 'view',type: 'string'}
          ]
          ,
	  listeners: {
	      save: function(s, b, d) {
	    	  store.save();
	      }
	  },
    writer: writer
});

var filters = new Ext.ux.grid.GridFilters({
    // encode and local configuration options defined previously for easier reuse
    encode: true, // json encode the filter query
    local: true,   // defaults to false (remote filtering)
    filters: [
        {type: 'string',dataIndex: 'name'},
        {type: 'string',dataIndex: 'email'},
        {type: 'string',dataIndex: 'company'},
        {type: 'string',dataIndex: 'message_subject'},
        {type: 'date',dataIndex: 'contact_day'},
        {type: 'list',dataIndex: 'status',options: [[1,'new'],[2,'processing'],[3,'finish']],phpMode: true}
    ]
});
var createColModel = function () {
    var columns = [
        {header: 'ID',sort: 'id',dataIndex: 'id'},
        {header: 'Contact day',renderer: formatDate,sortable: true,sort: 'contact_day',dataIndex: 'contact_day'},
        {header: 'Name',sortable: true,sort: 'name',dataIndex: 'name'},
        {header: 'Email',sortable: true,sort: 'email',dataIndex: 'email'},
        {header: 'Company',sortable: true,sort: 'company',dataIndex: 'company'},
        {header: 'Message Subject',sortable: true,sort: 'message_subject',dataIndex: 'message_subject'},
        {header: 'View',dataIndex: 'view',sortable: false}
        
         ];
 if (order_status == 'processing'){
        columns.push({
            header: 'Status',
            xtype: 'actioncolumn',
            width: 50,
            items: [
                {
                    icon   : '/extjs/finish.gif',
                    altText : 'Finish',
                    tooltip: 'Finish this contact',
                    handler: function(grid, rowIndex, colIndex) {
                        var rec = store.getAt(rowIndex);
                        Ext.MessageBox.show({title:'Status Change',buttons: Ext.MessageBox.YESNO,animEl: 'samplebutton',icon: Ext.MessageBox.QUESTION,
                            msg: 'Do you really want to set status of this contact to "Finish"?',
                            fn:function(buttonId){
                                if (buttonId == 'yes'){
                                    Ext.Ajax.request({
                                       url: base_url+'admin/contact/update_status.html',
                                       success: function(response, opts) {
                                            store.reload({params:{start:0, limit:total_row}});
                                       },
                                       params: { id: rec.get('id'),status:'finish' },
                                       method:'GET'
                                    });
                                }
                            }
                        });
                    }
                }
            ]        
         });
    }
 
    return new Ext.grid.ColumnModel({
        columns: columns,
        defaults: {
            sortable: true
        }
    });
};
pagingBar = new Ext.PagingToolbar({
            store: store,
            pageSize: total_row,
            displayInfo: true,            
            displayMsg: 'Displaying item {0} - {1} of {2}',
            emptyMsg: "No item to display",
            plugins: new Ext.ux.ProgressBarPager()
        });
Ext.onReady(function() {
    Ext.QuickTips.init();

    var newsGrid = new Ext.grid.GridPanel({
        renderTo: 'news-grid',
        iconCls: 'icon-grid',
        frame: true,        
        height: 300,
        store: store,
        clicksToEdit:1,
        plugins: [filters],
        colModel: createColModel(),
        listeners: {
            render: {
                fn: function(){
                    store.load({
                        params: {
                            start: 0,
                            limit: total_row
                        }
                    });
                }
            }
        },
        tbar: [new Ext.form.ComboBox({
                     triggerAction: 'all',
                     lazyRender:false,
                     width:40,
                     mode: 'local',
                     store: new Ext.data.ArrayStore({
                         fields: [
                                  'id',
                                  'value'
                                 ],
                        data: [[10,'10'],[20,'20'],[50,'50'],[100,'100']]
                     }),
                     valueField: 'id',
                     displayField: 'value',
                     listeners:{
                          'select': function(combo,record ,index){
                        	  total_row = combo.getValue();
                        	  store.reload({params:{start:0, limit:total_row}});
                                  pagingBar.pageSize = total_row;
                        	  pagingBar.render();
                          }
                     }
                })
        ,'-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: onDelete
        }, '-'],
        bbar: pagingBar,
        viewConfig: {
            forceFit: true
        }
    });
    
    function onDelete() {
        Ext.MessageBox.show({
            title:'Delete item',
            msg: 'Do you really want to delete this contact ?',
            buttons: Ext.MessageBox.YESNO,
            animEl: 'samplebutton',
            icon: Ext.MessageBox.QUESTION,
            fn:function(buttonId){
                if (buttonId == 'yes'){
                    var recs = newsGrid.getSelectionModel().getSelections() ;
                    if (!recs) {
                        return false;
                    }
                    for(var i in recs)
                    {
                        newsGrid.store.remove(recs[i]);
                    }
                }
            }
        });
    }
});
function formatDate(value){
    return value ? value.dateFormat('d-m-Y') : '';
}
function formatLanguage(value){
	if(value!='')
		return eval('langList.'+value);
	else return '';
}
        
function thickBoxPopup(id){
    Ext.Ajax.request({
       url: base_url+'admin/contact/details_contact.html',
       success: function(response, opts) {
           var win = new Ext.Window({
                title: 'Contact Detail',
                resizable:false,
                preventBodyReset:true,
                bodyStyle:'background-color: #FFF',
                width:600,                
                html: response.responseText,
                listeners:{
                      'close': function(){
                            if (order_status == 'new'){
                                store.reload({params:{start: 0,limit: total_row}});
                            }
                      }
                }
            });
            win.show();
        },
       params: { id: id },
       method:'GET'
    });
}